package com.example.administrator.szb.fragments.fragment_forMy;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.example.administrator.szb.R;
import com.example.administrator.szb.activity.WTContentActivity;
import com.example.administrator.szb.adapter.BaseAdapter;
import com.example.administrator.szb.adapter.MyOnScroll;
import com.example.administrator.szb.fragments.base.BaseFragment;
import com.example.administrator.szb.bean.WDGLBean;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.GetJsonDataUtil;
import com.example.administrator.szb.util.Toasts;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by D N on 2017/9/29.
 * 兄嘚，如果仔细看了这fragment你就会觉得很奇怪，为什么后台给了putForward，receive，answer三个集合，而我只用了putForward这个字段呢？
 * 因为你会发现这三个集合的字段是一模一样的！后台为什么这样给，我也不知道。。。。为了减少工作量，我在GsonRequest.java这个类中做了字段替换
 * 在protected Response<T> parseNetworkResponse(NetworkResponse response) {}方法中，祝你好心情。。。反正我是日了狗了。。。
 */

public class FragmentWDGL extends BaseFragment {
    View view;
    @Bind(R.id.wdgl_fragment)
    RecyclerView wdglFragment;
    private int type = 1;//表示,1我提出的问题，2我收到的问题，3我回答的问题
    private View footerview;

     public  ArrayList<WDGLBean.DataBean.PutForwardBean> mdata = new ArrayList<>();
     public  BaseAdapter<WDGLBean.DataBean.PutForwardBean> adapter;

    private int current_page = 1;//列表当前页
    private int per_page = 10;//默认展示条数

    public static ArrayList<String> refer_id = new ArrayList<String>(){
        @Override
        public String toString() {
            String s= "";
            for (String info: refer_id) {
                s = s+ info+",";
            }
            return s;
        }
    };

    private WDGLBean mYcollectionbean;
    View error_head;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.wdgl_fragment, container, false);
        ButterKnife.bind(this, view);
        mdata.clear();
        footerview = LayoutInflater.from(getActivity()).inflate(R.layout.view_wd_footer, null);
        footerview.setVisibility(View.INVISIBLE);
        requsetMyAnswer();
        return view;
    }
    private void initView() {
        //initTabLayout();
        //initRecyclerview();

    }
    /**
     * 初始化列表
     */
    private void initRecyclerview() {

        initAdapter();

        wdglFragment.setLayoutManager(new LinearLayoutManager(getActivity()));

        if (mdata.size() == 0){
            error_head = LayoutInflater.from(getActivity()).inflate(R.layout.view_item_error, wdglFragment, false);
            adapter.addHeaderView(error_head);

            String info = "";
            switch (type){
                case 1:
                    info = "您还没有提出问题哦";
                    break;
                case 2:
                    info = "尚未有他人向您提出问题";
                    break;
                case 3:
                    info = "您尚未回答任何问题";
                    break;
            }

            ((TextView)error_head.findViewById(R.id.text_view_error)).setText(info);
        }else{
            adapter.addFootView(footerview);
            loadMore();//开启加载更多监听
        }


        wdglFragment.setAdapter(adapter);

    }
    /**
     * 开启加载更多
     */
    private void loadMore() {

        wdglFragment.addOnScrollListener(new MyOnScroll(){
            @Override
            public void scrollBottom() {

                    super.scrollBottom();
                    footerview.setVisibility(View.VISIBLE);
                   requsetMyAnswer();

            }
        });
    }

    /**
     * 初始化recyclerview的adapter
     */

    private void initAdapter() {
        adapter = new BaseAdapter<WDGLBean.DataBean.PutForwardBean>(getActivity(),mdata,true) {
            @Override
            public void convert(int position, BaseViewHolder holder, WDGLBean.DataBean.PutForwardBean referBean) {
                initItem(holder,referBean);
            }

            @Override
            public int getLayoutId(int viewType) {
                return R.layout.view_my_collection_item;
            }
        };


        /**
         * 添砖到问题详情，回答问题
         */
        adapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(getActivity(), WTContentActivity.class);
                //SampleApplicationLike.getQueueInstance().cancelAll("tag");
                intent.putExtra("refer_id",mdata.get(position).getId());
                startActivity(intent);
            }
        });

    }

    private void initItem(final BaseAdapter<WDGLBean.DataBean.PutForwardBean>.BaseViewHolder holder, final WDGLBean.DataBean.PutForwardBean referBean) {
        ((CheckBox)holder.getView(R.id.checkBox3)).setChecked(referBean.isChoose());
        if (referBean.getIsShowCheckBod() == View.VISIBLE){
            ((CheckBox)holder.getView(R.id.checkBox3)).setVisibility(View.VISIBLE);
        }else{
            ((CheckBox)holder.getView(R.id.checkBox3)).setVisibility(View.GONE);
        }

        ((CheckBox)holder.getView(R.id.checkBox3)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    refer_id.add(referBean.getId()+"");
                }else{
                    refer_id.remove(referBean.getId()+"");
                }
            }
        });

        /**
         * todo 填充数据
         */
        ((TextView)holder.getView(R.id.textView63)).setText(referBean.getTitle());
        ((TextView)holder.getView(R.id.textView64)).setText(referBean.getCollect_count()+"收藏");
        ((TextView)holder.getView(R.id.textView65)).setText(referBean.getAnswer_count()+"回答");
        ((TextView)holder.getView(R.id.textView66)).setText(referBean.getCreate_time());
    }




    /**
     * 我的问题请求
     */
    private void requsetMyAnswer() {
        type = getArguments().getInt("type");
        HashMap<String,String> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("users_id", SampleApplicationLike.getUserloginInstance().getId()+"");
        map.put("genre","" + type);
        map.put("current_page",current_page+"");
        map.put("per_page",per_page+"");

        String json = GetJsonDataUtil.simpleMapToJsonStr(map);

        String url = URLAddress.URLBASE +URLAddress.URL_WDGL_New;
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, WDGLBean.class, url, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                mYcollectionbean = (WDGLBean) response;
                if (mYcollectionbean.getResult() == 1 && current_page == 1){
                    List l = mYcollectionbean.getData().getPutForward();
                    if (l==null){
                        l = new ArrayList();
                    }
                    mdata.addAll(l);
                    current_page = current_page + 1;
                    initRecyclerview();
                    initView();
                }else if(mYcollectionbean.getResult() == 1){
                    current_page = current_page + 1;
                    List l = mYcollectionbean.getData().getPutForward();
                    if (l==null){
                        l = new ArrayList();
                    }
                    mdata.addAll(l);
                    //mdata.addAll(mYcollectionbean.getData().getPutForward());
                    adapter.notifyDataSetChanged();
                    footerview.setVisibility(View.INVISIBLE);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                footerview.setVisibility(View.INVISIBLE);
                error.toString();
                Toasts.show(getActivity(), "没有数据了", Toast.LENGTH_SHORT);
            }
        });
    }



    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
